package com.zc.serveudpdemo.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 功能描述：服务端
 *
 * @author：ZC 创建时间：2019/6/27 8:01
 * 最后修改日期：
 */
public class ServeUdp {

    //服务器IP
    private final String SERVER_IP = "127.0.0.1";
    //远程端口
    private final int REMOTE_PORT = 5600;
    //端口
    private DatagramSocket mDatagramSocket;
    private String edIpStr = null;

    /**
     * @brief 构造函数
     */
    public ServeUdp(String ipStr) {
        try {
            this.edIpStr = ipStr;
            //端口
            mDatagramSocket = new DatagramSocket();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param data:需要发送的数据
     * @param len:数据字节数据
     * @brief 发送数据
     */
    public void send(final byte[] data, final int len) {
        DatagramPacket mDatagramPacket = new DatagramPacket(data, len);
        try {
            mDatagramPacket.setPort(REMOTE_PORT);
            if (edIpStr == null) {
                mDatagramPacket.setAddress(InetAddress.getByName(SERVER_IP));
            } else {
                mDatagramPacket.setAddress(InetAddress.getByName(edIpStr));
            }
            mDatagramSocket.send(mDatagramPacket);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        if (mDatagramSocket != null) {
            mDatagramSocket.close();
            mDatagramSocket = null;
        }
    }
}
